package com.uinnova.product.eam.db.support.util;

import com.binary.core.lang.Conver;
import com.binary.core.util.BinaryUtils;
import com.binary.framework.exception.DaoException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class ResultSetConvertUtil {
    
    private static final Logger logger = LoggerFactory.getLogger(ResultSetConvertUtil.class);
	
	
    /**把resultSet通过反射转换为指定的JAVA Bean List
     * @param resultSet
     * @param beanClass 
     * @return
     * @throws Exception
     */
    public static <T> List<T> getBeanList(ResultSet resultSet, Class<T> beanClass){
        List<T> list = new ArrayList<T>();
        Field fields[] = beanClass.getDeclaredFields();
        
        Map<String,Field> mapFields = new HashMap<String,Field>();
        for(Field field : fields) {
        	String fieldName = field.getName().toUpperCase();
        	mapFields.put(fieldName, field);
        }
        
    	ResultSetMetaData metaData;
        try {
            metaData = resultSet.getMetaData();
            int count = metaData.getColumnCount();
    	
            while (resultSet.next()) {
                T instance = beanClass.newInstance();
                
                for (int i=1; i<=count; i++) {
                    try {
                        String columnName = metaData.getColumnName(i).replace("_", "").replace("-", "").toUpperCase();
                        Object columnData = resultSet.getObject(i);

                        if (mapFields.containsKey(columnName)) {
                            Field field = mapFields.get(columnName);
                            Type fieldType = field.getGenericType();
                            // 数据类型转换
                            Object fieldData = Conver.mapping(fieldType, columnData);
                            boolean flag = field.isAccessible();
                            field.setAccessible(true);
                            field.set(instance, fieldData);
                            field.setAccessible(flag);
                        }
                    } catch (Exception exp) {
                        logger.warn(exp.getMessage());
                    }
                }
                
                list.add(instance);
            }
        } catch (Exception e) {
            BinaryUtils.transException(e, DaoException.class);
        }

        return list;
    }
 
    
    /**把List<Map>通过反射转换为指定的List<Bean>
     * @param listMap
     * @param beanClass 
     * @return
     * @throws Exception
     */
    public static <T> List<T> getMap2BeanList(List<Map<String,Object>> listMap, Class<T> beanClass){
        List<T> list = new ArrayList<T>();
        Field fields[] = beanClass.getDeclaredFields();
        
        Map<String,Field> mapFields = new HashMap<String,Field>();
        for(Field field : fields) {
        	String fieldName = field.getName().toUpperCase();
        	mapFields.put(fieldName, field);
        }
        
        if (listMap != null && listMap.size() > 0) {
            for (int i = 0; i < listMap.size(); i++) {
                Map<String, Object> mapData = listMap.get(i);
                Iterator<String> itKeys = mapData.keySet().iterator();
                try {
                    T instance = beanClass.newInstance();
                    while (itKeys.hasNext()) {
                        String strKey = itKeys.next();
                        String strFieldKey = strKey.replace("_", "").replace("-", "").toUpperCase();

                        if (mapFields.containsKey(strFieldKey)) {
                            Field field = mapFields.get(strFieldKey);
                            Type fieldType = field.getGenericType();
                            Object columnData = mapData.get(strKey);
                            // 数据类型转换
                            Object fieldData = Conver.mapping(fieldType, columnData);
                            boolean flag = field.isAccessible();
                            field.setAccessible(true);
                            field.set(instance, fieldData);
                            field.setAccessible(flag);
                        }
                    }

                    list.add(instance);

                } catch (Exception e) {
                    BinaryUtils.transException(e, DaoException.class);
                }
            }
        }

        return list;
    }
    
    /**把resultSet通过反射转换为指定的JAVA Bean
     * @param resultSet
     * @param beanClass
     * @return
     * @throws Exception
     */
    public static <T> T getBean(ResultSet resultSet, Class<T> beanClass) throws Exception {
    	
        Field fields[] = beanClass.getDeclaredFields();
        
        Map<String,Field> mapFields = new HashMap<String,Field>();
        for(Field field : fields) {
        	String fieldName = field.getName().toUpperCase();
        	mapFields.put(fieldName, field);
        }
        
        //获取字段
    	ResultSetMetaData metaData = resultSet.getMetaData();
    	int count = metaData.getColumnCount();
    	
    	
        T instance = null;

        instance = beanClass.newInstance();
        
        for (int i=1; i<=count; i++) {
        	try {
//            	String columnName = metaData.getColumnName(i).replace("_", "").replace("-", "").toUpperCase();
            	String columnName = metaData.getColumnLabel(i).replace("_", "").replace("-", "").toUpperCase();
            	Object columnData = resultSet.getObject(i);
            	
            	if(mapFields.containsKey(columnName)) {
            		Field field = mapFields.get(columnName);
            		Type fieldType = field.getGenericType();
            		//数据类型转换
            		Object fieldData = Conver.mapping(fieldType, columnData);
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    field.set(instance, fieldData);
                    field.setAccessible(flag);             		
            	}           		
        	}catch(Exception exp) {
        		System.out.println(exp.getMessage());
        	}
        }          
        
        return instance;
    }  
    
    /**把resultSet转换为Map List
     * @param resultSet
     * @param beanClass 
     * @return
     * @throws Exception
     */
    public static List<Map<String,Object>> getMapList(ResultSet resultSet) throws Exception {
    	List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
    	
    	ResultSetMetaData metaData = resultSet.getMetaData();
    	int count = metaData.getColumnCount();
    	
        while (resultSet.next()) {
        	Map<String,Object> mapData = new HashMap<String,Object>();        	
        	
            for (int i=1; i<=count; i++) {
//            	String columnName = metaData.getColumnName(i).replace("_", "").replace("-", "").toUpperCase();
            	String columnName = metaData.getColumnLabel(i).replace("_", "").replace("-", "").toUpperCase();
            	Object columnData = resultSet.getObject(i);
            	
            	mapData.put(columnName, columnData);

            }
            list.add(mapData);
        }
        return list;
    }  
    
    /**把resultSet转换为Map
     * @param resultSet
     * @return
     * @throws Exception
     */
    public static Map<String,Object> getMap(ResultSet resultSet) throws Exception {

    	ResultSetMetaData metaData = resultSet.getMetaData();
    
    	int count = metaData.getColumnCount();
  
    	Map<String,Object> mapData = new HashMap<String,Object>();        	
    	
        for (int i=0; i<count; i++) {
//        	String columnName = metaData.getColumnName(i).replace("_", "").replace("-", "").toUpperCase();
        	String columnName = metaData.getColumnLabel(i).replace("_", "").replace("-", "").toUpperCase();
        	Object columnData = resultSet.getObject(i);
        	
        	mapData.put(columnName, columnData);
        }

        return mapData;
    }  
    
}
